package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.dtos.LoginDto;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper userMapper;

    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.判断是用户直接登录还是游客我先看看
        String phone = loginDto.getPhone();
        String password = loginDto.getPassword();
        //用户登录
        if (phone!=null&&phone!=""&&password!=null&&password!=""){
            //2.通过手机号查找到用户
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,phone);
            ApUser user = getOne(wrapper);
            if (user== null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有用户数据");
            }
            //3.拿到用户的盐和密码
            String salt = user.getSalt();
            //4.把客户端拿到的密码加盐进行加密和用户的密码进行比对
            password = DigestUtils.md5DigestAsHex((password+salt).getBytes());
            if (!password.equals(user.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //5.密码正确通过用户id生成token
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(user.getId().longValue()));
            //将盐和密码设置为空，避免数据泄露
            user.setSalt("");
            user.setPassword("");
            map.put("user",user);
            return ResponseResult.okResult(map);
        }
        //游客：我先看看
        else{
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 用户注册,发送短信
     *
     * @param phone
     * @param session
     * @return
     */
    @Override
    public ResponseResult registered(String phone, HttpSession session) {
        phone ="18080402494";
        if (phone.length() != 11){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请输入正确的手机号码");
        }
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser apUser = userMapper.selectOne(wrapper);
        if (apUser!= null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机号已被注册，请直接登录");
        }
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString().substring(1, 6);
        SendSms.sendMsg(phone,s);
        session.setAttribute(phone,s);
        log.info(s);
        HashMap<String, String> map = new HashMap<>();
        map.put(phone,s);
        return ResponseResult.okResult(map);
    }

    /**
     * 验证
     * @param phone
     * @param code
     * @param session
     * @return
     */
    @Override
    public ResponseResult validation(String phone, String code, HttpSession session) {
        String attribute = (String) session.getAttribute(phone);
        if (!attribute.equals(code)){
            return ResponseResult.errorResult(AppHttpCodeEnum.SIGN_INVALID,"验证码错误");
        }
        return ResponseResult.okResult("验证码正确，请填写个人信息");
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult regist(ApUser user) {
        ApUser apUser = new ApUser();
        //设置盐
        String s = UUID.randomUUID().toString().substring(1, 6);
        apUser.setSalt(s);
        //设置密码
        String password = DigestUtils.md5DigestAsHex((user.getPassword() + s).getBytes());
        apUser.setPassword(password);
        apUser.setName(user.getName());
        apUser.setPhone(user.getPhone());
        apUser.setSex(true);
        apUser.setCertification(false);
        apUser.setIdentityAuthentication(false);
        apUser.setStatus(true);
        apUser.setCreatedTime(new Date());
        userMapper.insert(apUser);
        return ResponseResult.okResult(apUser);
    }


}
